package xyz.scootaloo.oj.iq

import org.junit.Test

/**
 * @author flutterdash@qq.com
 * @since 2021/4/16 14:44
 */
class M0107 {

    /**
     * 1, 2, 3     7, 4, 1
     * 4, 5, 6     8, 5, 2
     * 7, 8, 9     9, 6, 3
     */
    private fun rotate(matrix: Array<IntArray>) {
        var sideLen = matrix.size
        var point = 0
        while (point <= matrix.size / 2) {
            spin(matrix, point, sideLen)
            sideLen -= 2
            point++
        }
    }

    private fun spin(matrix: Array<IntArray>, point: Int, sideLen: Int) {
        if (sideLen <= 1)
            return
        for (count in 0 until (sideLen - 1)) {
            spinCore(matrix, point, sideLen - 1, count)
        }
    }

    private fun spinCore(matrix: Array<IntArray>, point: Int, sideLen: Int, count: Int) {
        // 保存上边的点
        val tmp = matrix[point][point + count]
        // 上边的点被左边的点替换
        matrix[point][point + count] = matrix[point + sideLen - count][point]
        // 左边的点被下边替换
        matrix[point + sideLen - count][point] = matrix[point + sideLen][point + sideLen - count]
        // 下边被右边替换
        matrix[point + sideLen][point + sideLen - count] = matrix[point + count][point + sideLen]
        // 右边被上边替换
        matrix[point + count][point + sideLen] = tmp
    }

    @Test
    fun test0() {
        val res = arrayOf(
            intArrayOf(1, 2, 3),
            intArrayOf(4, 5, 6),
            intArrayOf(7, 8, 9)
        )
        rotate(res)
        for (array in res)
            println(array.contentToString())
    }

    @Test
    fun test1() {
        val res = arrayOf(
            intArrayOf(1, 2, 3, 4),
            intArrayOf(5, 6, 7, 8),
            intArrayOf(9, 10, 11, 12),
            intArrayOf(13, 14, 15, 16)
        )
        rotate(res)
        for (array in res)
            println(array.contentToString())
    }

}
